﻿'Programmer: Scuba156
'Program Name: Batch Con Flag Remover

Imports System.IO
Imports X360
Imports Microsoft.VisualBasic.FileIO


Public Class Main
    Dim myBrush As Brush = Brushes.Black
    Private counter1 As Integer
    Friend Backup As Boolean = True
    Friend STFSFilePath As Object
    Dim sortColumn As Integer = -1
    Friend counter As Integer = 0
    Friend DeviceID, ConsoleID, ProfileID As String

    Public Sub New()
        InitializeComponent()
        X360.XAbout.WriteLegalLocally()
    End Sub

    Private Sub OpenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenButton.Click
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            SavesListView.Sorting = SortOrder.None
            GetFiles.FolderPath = FolderBrowserDialog1.SelectedPath
            GetSaves()
            If SavesListView.Items.Count <> -1 Then
                BackupsCheckBox.Enabled = True
                UnflagButton.Enabled = True
                ResignCheckBox.Enabled = True
                RestoreBackupsToolStripMenuItem.Enabled = True
            End If

        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        LogListBox.Items.Add("Xbox1Crew Presents Batch Con Flag Remover")
        LogListBox.Items.Add("Batch Con Flag Remover Started...")
        LogListBox.Items.Add("   Click Add to select a folder to start...")
        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
        LogListBox.SelectedIndex = -1

        AddHandler SavesListView.ColumnClick, AddressOf SavesListView_ColumnClick
        'Dim SettingsFieldParser As TextFieldParser
        'Dim FileString As String = "Config.ini"
        Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Config.ini")
            MyReader.TextFieldType = FileIO.FieldType.Delimited
            MyReader.SetDelimiters("=")
            Dim currentRow As String()
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields()
                    If currentRow(0) = "DeviceID" Then
                        DeviceID = currentRow(1)
                    ElseIf currentRow(0) = "ProfileID" Then
                        ProfileID = currentRow(1)
                    ElseIf currentRow(0) = "ConsoleID" Then
                        ConsoleID = currentRow(1)
                    End If
                    'Dim currentField As String
                    'For Each currentField In currentRow
                    '    MsgBox(currentField)
                    'Next
                Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
                End Try
            End While
        End Using


    End Sub

    Private Sub UnflagButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UnflagButton.Click
        SavesListView.Sorting = SortOrder.None
        Dim BackupCount As Integer = 0
        Dim FlagCount As Integer = 0

        counter = 0
        If Backup = False Then
            If MessageBox.Show("Are you aure you want to overwrite without creating a backup first?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.No Then
                Exit Sub
            End If

        End If

        Do Until counter = SavesListView.Items.Count
            Try
                'Dim h As New STFS.HeaderData()
                If SavesListView.Items(counter).SubItems(1).Text <> "FFFFFFFFFFFFFFFF" Then
                    If Backup = True Then

                        Dim testflag As String
                        Dim sr As BinaryReader = New BinaryReader(File.Open(SavesListView.Items(counter).SubItems(2).Text, FileMode.Open))
                        sr.BaseStream.Seek(556, SeekOrigin.Begin)
                        FlagFind = System.Net.IPAddress.HostToNetworkOrder(sr.ReadInt64())

                        testflag = Hex(FlagFind)
                        sr.Close()

                        If testflag <> "FFFFFFFFFFFFFFFF" Then
                            My.Computer.FileSystem.CopyFile(SavesListView.Items(counter).SubItems(2).Text, SavesListView.Items(counter).SubItems(2).Text & ".bak", True)
                            LogListBox.Items.Add("   Created backup " & SavesListView.Items(counter).SubItems(2).Text & ".bak")
                            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                            LogListBox.SelectedIndex = -1
                            BackupCount += 1
                        End If
                    End If
                    Dim fs As New FileStream(SavesListView.Items(counter).SubItems(2).Text, FileMode.Open, FileAccess.ReadWrite)
                    fs.Seek((556), SeekOrigin.Current)
                    Dim i As Integer = 0
                    Do While i <> 8

                        fs.WriteByte(&HFF)

                        i += 1
                    Loop
                    fs.Close()

                    LogListBox.Items.Add("   Removed flag in " & SavesListView.Items(counter).Text)
                    LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                    LogListBox.SelectedIndex = -1
                    FlagCount += 1

                    If ResignCheckBox.Checked = True Then
                        STFSFilePath = SavesListView.Items(counter).SubItems(2).Text
                        Mod_App.OpenResign(SavesListView.Items(counter).SubItems(2).Text, e)

                    End If
                End If
            Catch ex As Exception

                counter1 = counter
                'LogListBox_DrawItem(sender, e)
                LogListBox.Items.Add("   Error removing flag in " & SavesListView.Items(counter).Text & ":: " & Environment.NewLine & ex.Message)
                'Graphics.DrawString(LogListBox.Items.Add("   Error removing flag in " & SavesListView.Items(counter).Text), Font, myBrush, Bounds, StringFormat.GenericDefault)

                LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                LogListBox.SelectedIndex = -1
            End Try





            counter += 1
        Loop
        'GetSaves()
        If FlagCount = 1 Or BackupCount = 1 Then
            LogListBox.Items.Add("   " & BackupCount & " backup created")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1

            LogListBox.Items.Add("   " & FlagCount & " flag edited")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1

        Else
            LogListBox.Items.Add("   " & BackupCount & " backups created")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1

            LogListBox.Items.Add("   " & FlagCount & " flags edited")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1

        End If

        LogListBox.Items.Add("done.")
        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
        LogListBox.SelectedIndex = -1
        RefreshList()
    End Sub

    Private Sub BackupsCheckBox_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BackupsCheckBox.CheckedChanged
        Backup = BackupsCheckBox.Checked
    End Sub

    Private Sub LogListBox_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles LogListBox.DrawItem



        ' Draw the background of the ListBox control for each item.
        e.DrawBackground()

        ' Define the default <strong class="highlight">color</strong> of the brush as black.
        'Dim myBrush As Brush = Brushes.Black

        ' Determine the <strong class="highlight">color</strong> of the brush to draw each item based on   
        ' the index of the item to draw.
        'Select Case e.Index

        '   Case 1
        'myBrush = Brushes.Orange

        'End Select

        ' Draw the current item text based on the current 
        ' <strong class="highlight">Font</strong> and the custom brush settings.
        myBrush = Brushes.Red
        e.Graphics.DrawString(LogListBox.Items.Add("   Error removing flag in " & SavesListView.Items(counter1).Text), _
            e.Font, myBrush, e.Bounds, StringFormat.GenericDefault)
        myBrush = Brushes.Black
        ' If the ListBox has focus, draw a focus rectangle around  _ 
        ' the selected item.
        e.DrawFocusRectangle()




    End Sub

    Friend Sub SavesListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs)
        ' Determine whether the column is the same as the last column clicked.
        If e.Column <> sortColumn Then
            ' Set the sort column to the new column.
            sortColumn = e.Column
            ' Set the sort order to ascending by default.
            SavesListView.Sorting = SortOrder.Ascending
        Else
            ' Determine what the last sort order was and change it.
            If SavesListView.Sorting = SortOrder.Ascending Then
                SavesListView.Sorting = SortOrder.Descending
            Else
                SavesListView.Sorting = SortOrder.Ascending
            End If
        End If
        ' Call the sort method to manually sort.
        SavesListView.Sort()
        ' Set the ListViewItemSorter property to a new ListViewItemComparer
        ' object.
        SavesListView.ListViewItemSorter = New ListViewItemComparer(e.Column, SavesListView.Sorting)
    End Sub

    Private Sub RemoveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveButton.Click
        'For Each selection In SavesListView.SelectedIndices.Count()
        For Each Save As ListViewItem In SavesListView.SelectedItems
            Save.Remove()
        Next

        If SavesListView.Items.Count = -1 Then
            BackupsCheckBox.Enabled = False
            UnflagButton.Enabled = False
            ResignCheckBox.Enabled = False
            RestoreBackupsToolStripMenuItem.Enabled = False
        End If
        ' Next
    End Sub

    Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
        Me.Close()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub AddToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddToolStripMenuItem.Click
        OpenButton_Click(sender, e)
    End Sub

    Private Sub RestoreBackupsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestoreBackupsToolStripMenuItem.Click
        If MessageBox.Show("WARNING: will revert files to there backup file, are you sure?", "Are You sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) Then
            Dim itemscount As Integer = 0
            Do Until itemscount = SavesListView.Items.Count
                If File.Exists(SavesListView.Items(itemscount).SubItems(2).Text & ".bak") Then
                    My.Computer.FileSystem.CopyFile(SavesListView.Items(itemscount).SubItems(2).Text & ".bak", SavesListView.Items(itemscount).SubItems(2).Text, True)
                    LogListBox.Items.Add("   Restored Backup " & SavesListView.Items(itemscount).SubItems(2).Text & ".bak")
                    LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                    LogListBox.SelectedIndex = -1
                    itemscount += 1
                Else
                    itemscount += 1
                End If
            Loop
        End If
        RefreshList()
    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        AboutBox.ShowDialog()
    End Sub

    Private Sub SetIDsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetIDsToolStripMenuItem.Click
        SetIDDialog.ShowDialog()
    End Sub
End Class
